package com.haidechizi.i18n.spring.boot.autoconfigure;

import com.haidechizi.i18n.interceptor.I18nInterceptor;
import com.haidechizi.i18n.spring.boot.properties.I18nProperties;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
@EnableConfigurationProperties(I18nProperties.class)
public class I18nAopAutoConfiguration {

    @Autowired
    private I18nProperties i18nProperties;

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnClass(MethodInterceptor.class)
    public DefaultPointcutAdvisor defaultPointcutAdvisor() {
//        String execution = "@annotation(com.haidechizi.i18n.annotation.I18nAnnotation) || @within(com.haidechizi.i18n.annotation.I18nAnnotation)";
        String execution = i18nProperties.getAopExecution();
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(execution);

        // 配置增强类advisor
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        advisor.setAdvice(i18nInterceptor());
        return advisor;
    }

    @Bean
    public I18nInterceptor i18nInterceptor() {
        return new I18nInterceptor();
    }
}
